package com.itheima.es.service.impl;

import com.alibaba.fastjson.JSON;
import com.hmall.common.dto.PageDTO;
import com.hmall.common.es.ItemDoc;
import com.hmall.common.pojo.Item;
import com.hmall.feignclient.ItemFeignClient;
import com.itheima.es.service.ItemSearchService;
import com.itheima.es.vo.SearchVO;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.range.ParsedRange;
import org.elasticsearch.search.aggregations.bucket.range.Range;
import org.elasticsearch.search.aggregations.bucket.range.RangeAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 苏成博
 * @date 2023-03-18 21:14
 */
@Service
public class ItemSearchServiceImpl implements ItemSearchService {
    @Autowired
    private RestHighLevelClient client;
    @Autowired
    private ItemFeignClient itemFeignClient;

    @Override
    public PageDTO<ItemDoc> listSearchItem(SearchVO searchVO) {
        try {
            SearchRequest searchRequest = new SearchRequest("item");
            searchRequest.source()
                    .from((searchVO.getPage() - 1) * searchVO.getSize())
                    .size(searchVO.getSize()).highlighter(
                    new HighlightBuilder().field("name")
                            .requireFieldMatch(false));
            String sortBy = searchVO.getSortBy();
            //按库存倒序排序
            if (StringUtils.isNotEmpty(sortBy) && "sold".equals(sortBy)) {
                searchRequest.source().sort("sold", SortOrder.DESC);
            }
            //按价格倒序排序
            if (StringUtils.isNotEmpty(sortBy) && "price".equals(sortBy)) {
                searchRequest.source().sort("price", SortOrder.DESC);
            }
            BoolQueryBuilder boolQueryBuilder = getBoolQueryBuilder(searchVO);
            /*FunctionScoreQueryBuilder functionScoreQueryBuilder = QueryBuilders.functionScoreQuery(
                    boolQueryBuilder, new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                            new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                    QueryBuilders.termQuery("isAD", true),
                                    ScoreFunctionBuilders.weightFactorFunction(10)
                            )
                    }
            );*/
            //searchRequest.source().query(functionScoreQueryBuilder);
            searchRequest.source().query(boolQueryBuilder);
            SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
            PageDTO<ItemDoc> pageDTO = parseJsonString(response);
            return pageDTO;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public Map<String, List<String>> filterSearch(SearchVO searchVO) {
        try {
            // 创建ES客户端
            SearchRequest request = new SearchRequest("item");
            // 分组查询
            SearchSourceBuilder builder = new SearchSourceBuilder();
            BoolQueryBuilder boolQueryBuilder = getBoolQueryBuilder(searchVO);

            builder.size(0);
            //分类品种
            TermsAggregationBuilder aggregationCategory = AggregationBuilders.terms("category").field("category");
            //品牌品种
            TermsAggregationBuilder aggregationBrand = AggregationBuilders.terms("brand").field("brand");
            //按价格画桶
            RangeAggregationBuilder aggregationPrice = AggregationBuilders.range("priceRanges")
                    .addUnboundedTo(100)
                    .addRange(100, 300)
                    .addRange(300, 600)
                    .addRange(600, 1500)
                    .addUnboundedFrom(1500)
                    .field("price");
            //加入builder
            builder.aggregation(aggregationCategory);
            builder.aggregation(aggregationBrand);
            builder.aggregation(aggregationPrice);
            request.source(builder).source().query(boolQueryBuilder);
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            // 查询命中的信息
            Aggregations aggregations = response.getAggregations();
            HashMap<String, List<String>> hashMap = new HashMap<>();
            List<String> priceList = new ArrayList<>();
            List<String> categoryList = new ArrayList<>();
            List<String> brandList = new ArrayList<>();
            for (Aggregation a : aggregations) {
                //如果是价格范围则进这个循环
                if (a instanceof ParsedRange) {
                    ParsedRange range = (ParsedRange) a;
                    for (Range.Bucket bucket : range.getBuckets()) {
                        String key = bucket.getKey().toString();
                        priceList.add(key);
                    }
                }
                //如果是品牌和种类则进这个
                if (a instanceof Terms) {
                    Terms range = (Terms) a;
                    String name = a.getName();
                    //如果是种类，则进这个
                    if (StringUtils.isNotEmpty(name) && name.equals("category")) {
                        for (Terms.Bucket bucket : range.getBuckets()) {
                            String key = bucket.getKey().toString();
                            categoryList.add(key);
                        }
                    }
                    //如果是品牌则进这个
                    if (StringUtils.isNotEmpty(name) && name.equals("brand")) {
                        for (Terms.Bucket bucket : range.getBuckets()) {
                            String key = bucket.getKey().toString();
                            brandList.add(key);
                        }
                    }
                }
            }
            hashMap.put("category", categoryList);
            hashMap.put("brand", brandList);
            //hashMap.put("price",priceList);
            return hashMap;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    private BoolQueryBuilder getBoolQueryBuilder(SearchVO searchVO) {
        //构建布尔排序条件
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        String key = searchVO.getKey();
        if (StringUtils.isNotEmpty(key)) {
            boolQueryBuilder.must(QueryBuilders.matchQuery("all", key));
        }
        String category = searchVO.getCategory();
        if (StringUtils.isNotEmpty(category)) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("category", category));
        }
        String brand = searchVO.getBrand();
        if (StringUtils.isNotEmpty(brand)) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("brand", brand));
        }
        Double minPrice = searchVO.getMinPrice();
        Double maxPrice = searchVO.getMaxPrice();
        if (minPrice != null && maxPrice != null) {
            boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").lte(maxPrice).gte(minPrice));
        }
        return boolQueryBuilder;
    }

    //解析es查询返回的参数
    private PageDTO<ItemDoc> parseJsonString(SearchResponse searchResponse) {
        //解析response
        //1.得到最大的searchHits
        SearchHits searchHits = searchResponse.getHits();
        //2.通过searchHits得到总条数
        long value = searchHits.getTotalHits().value;
        //System.out.println("总条数Total为：" + value);
        //得到和文档有关的数组
        SearchHit[] hits = searchHits.getHits();
        PageDTO<ItemDoc> pageDTO = new PageDTO<>();
        ArrayList<ItemDoc> itemDocs = new ArrayList<>();
        for (SearchHit hit : hits) {
            //得到具体的文档元素
            String sourceAsString = hit.getSourceAsString();
            //解析json
            ItemDoc itemDoc = JSON.parseObject(sourceAsString, ItemDoc.class);
            //获取高亮字段集合
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            if (!CollectionUtils.isEmpty(highlightFields)) {
                //获取指定的高亮字段
                HighlightField highlightField = highlightFields.get("name");
                if (highlightField != null) {
                    //获取es返回的高亮数据
                    String name = highlightField.getFragments()[0].string();
                    //设置进入HotelDoc中
                    itemDoc.setName(name);
                }
            }
            //将文档信息添加进集合
            itemDocs.add(itemDoc);
        }
        pageDTO.setList(itemDocs);
        pageDTO.setTotal(value);
        return pageDTO;
    }

}